#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
记录管理示例

这个脚本展示了如何在实际场景中使用记录操作功能，包括：
1. 批量创建不同类型的记录
2. 搜索和查询记录
3. 批量更新和删除记录
4. 记录的完整生命周期管理
"""

import sys
import os
import json
import uuid
import time
from typing import List, Dict, Any, Optional
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

from feishu_bitable_client import FeishuBitableClient
from config import Config

class RecordManager:
    """记录管理器"""
    
    def __init__(self, client: FeishuBitableClient, app_token: str, table_id: str):
        self.client = client
        self.app_token = app_token
        self.table_id = table_id
        self.created_records = []  # 记录创建的记录ID，便于清理
    
    def create_sample_records(self) -> List[Dict[str, Any]]:
        """创建示例记录"""
        print("📝 创建示例记录...")
        
        # 定义要创建的示例记录
        records_to_create = [
            {
                '编号': 'GOODS001',
                '商品名称': 'iPhone 15 Pro',
                '价格': 8999.00,
                '状态': '在售',
                '标签': ['热销', '新品'],
                '上架日期': '2024/01/15'
            },
            {
                '编号': 'GOODS002', 
                '商品名称': 'MacBook Air M3',
                '价格': 9499.00,
                '状态': '在售',
                '标签': ['热销', '限量'],
                '上架日期': '2024/02/01'
            },
            {
                '编号': 'GOODS003',
                '商品名称': 'AirPods Pro 2',
                '价格': 1899.00,
                '状态': '缺货',
                '标签': ['促销'],
                '上架日期': '2024/01/20'
            },
            {
                '编号': 'GOODS004',
                '商品名称': 'iPad Pro 12.9',
                '价格': 7999.00,
                '状态': '在售',
                '标签': ['新品'],
                '上架日期': '2024/02/10'
            },
            {
                '编号': 'GOODS005',
                '商品名称': 'Apple Watch Ultra 2',
                '价格': 6299.00,
                '状态': '下架',
                '标签': ['限量'],
                '上架日期': '2024/01/05'
            }
        ]
        
        created_records = []
        
        for i, record_data in enumerate(records_to_create, 1):
            try:
                print(f"   创建记录 {i}: {record_data.get('商品名称', 'N/A')}...")
                
                result = self.client.create_record(
                    app_token=self.app_token,
                    table_id=self.table_id,
                    fields=record_data
                )
                
                if result.get('code') == 0:
                    record_info = result.get('data', {}).get('record', {})
                    created_records.append(record_info)
                    record_id = record_info.get('record_id')
                    self.created_records.append(record_id)
                    print(f"   ✅ 成功创建: {record_data.get('商品名称')} (ID: {record_id})")
                else:
                    print(f"   ❌ 创建失败: {result.get('msg')}")
                    
                # 避免请求过于频繁
                time.sleep(0.5)
                    
            except Exception as e:
                print(f"   ❌ 创建记录时发生错误: {e}")
        
        print(f"\n✅ 成功创建 {len(created_records)} 条记录")
        return created_records
    
    def search_records_demo(self) -> List[Dict[str, Any]]:
        """搜索记录演示"""
        print("\n🔍 搜索记录演示...")
        
        # 演示不同的搜索条件
        search_scenarios = [
            {
                'name': '搜索所有在售商品',
                'filter': None,  # 不使用过滤条件，获取所有记录
                'page_size': 10
            },
            {
                'name': '搜索价格大于5000的商品',
                'filter': 'CurrentValue.[价格] > 5000',
                'page_size': 5
            }
        ]
        
        all_found_records = []
        
        for scenario in search_scenarios:
            try:
                print(f"\n   {scenario['name']}...")
                
                result = self.client.search_records(
                    app_token=self.app_token,
                    table_id=self.table_id,
                    filter_condition=scenario['filter'],
                    page_size=scenario['page_size']
                )
                
                if result.get('code') == 0:
                    records = result.get('data', {}).get('items', [])
                    print(f"   ✅ 找到 {len(records)} 条记录")
                    
                    for record in records:
                        fields = record.get('fields', {})
                        print(f"     - {fields.get('商品名称', 'N/A')} (价格: ¥{fields.get('价格', 'N/A')})")
                    
                    all_found_records.extend(records)
                else:
                    print(f"   ❌ 搜索失败: {result.get('msg')}")
                    
            except Exception as e:
                print(f"   ❌ 搜索时发生错误: {e}")
        
        return all_found_records
    
    def batch_get_records_demo(self, record_ids: List[str]) -> List[Dict[str, Any]]:
        """批量获取记录演示"""
        if not record_ids:
            print("\n📄 没有记录ID可供批量获取")
            return []
        
        print(f"\n📄 批量获取记录演示 (获取 {len(record_ids)} 条记录)...")
        
        try:
            # 只取前3个记录ID进行演示
            demo_ids = record_ids[:3]
            
            result = self.client.get_records(
                app_token=self.app_token,
                table_id=self.table_id,
                record_ids=demo_ids
            )
            
            if result.get('code') == 0:
                records = result.get('data', {}).get('records', [])
                print(f"   ✅ 成功获取 {len(records)} 条记录:")
                
                for record in records:
                    fields = record.get('fields', {})
                    print(f"     - ID: {record.get('record_id')}")
                    print(f"       商品: {fields.get('商品名称', 'N/A')}")
                    print(f"       状态: {fields.get('状态', 'N/A')}")
                    print(f"       价格: ¥{fields.get('价格', 'N/A')}")
                
                return records
            else:
                print(f"   ❌ 批量获取失败: {result.get('msg')}")
                return []
                
        except Exception as e:
            print(f"   ❌ 批量获取时发生错误: {e}")
            return []
    
    def update_records_demo(self, records: List[Dict[str, Any]]) -> None:
        """批量更新记录演示"""
        if not records:
            print("\n✏️ 没有记录可供更新")
            return
        
        print(f"\n✏️ 批量更新记录演示...")
        
        # 演示不同的更新场景
        update_scenarios = [
            {
                'condition': lambda r: r.get('fields', {}).get('状态') == '缺货',
                'updates': {'状态': '在售', '备注': '库存已补充'},
                'description': '将缺货商品状态更新为在售'
            },
            {
                'condition': lambda r: '促销' in r.get('fields', {}).get('标签', []),
                'updates': {'价格': lambda price: price * 0.8 if price else 0},  # 8折优惠
                'description': '对促销商品应用8折优惠'
            }
        ]
        
        for scenario in update_scenarios:
            print(f"\n   {scenario['description']}...")
            updated_count = 0
            
            for record in records:
                if scenario['condition'](record):
                    try:
                        record_id = record.get('record_id')
                        fields = record.get('fields', {})
                        
                        # 准备更新数据
                        update_fields = {}
                        for key, value in scenario['updates'].items():
                            if callable(value):
                                # 如果是函数，则应用到现有值
                                current_value = fields.get(key)
                                update_fields[key] = value(current_value)
                            else:
                                update_fields[key] = value
                        
                        print(f"     更新记录: {fields.get('商品名称', 'N/A')}...")
                        
                        result = self.client.update_record(
                            app_token=self.app_token,
                            table_id=self.table_id,
                            record_id=record_id,
                            fields=update_fields
                        )
                        
                        if result.get('code') == 0:
                            print(f"     ✅ 更新成功")
                            updated_count += 1
                        else:
                            print(f"     ❌ 更新失败: {result.get('msg')}")
                        
                        time.sleep(0.3)  # 避免请求过于频繁
                        
                    except Exception as e:
                        print(f"     ❌ 更新记录时发生错误: {e}")
            
            print(f"   ✅ 完成更新，共更新 {updated_count} 条记录")
    
    def cleanup_created_records(self) -> None:
        """清理创建的测试记录"""
        if not self.created_records:
            print("\n🧹 没有需要清理的记录")
            return
        
        print(f"\n🧹 清理 {len(self.created_records)} 条测试记录...")
        
        deleted_count = 0
        for record_id in self.created_records:
            try:
                result = self.client.delete_record(
                    app_token=self.app_token,
                    table_id=self.table_id,
                    record_id=record_id
                )
                
                if result.get('code') == 0:
                    print(f"   ✅ 成功删除记录: {record_id}")
                    deleted_count += 1
                else:
                    print(f"   ❌ 删除记录失败: {result.get('msg')}")
                
                time.sleep(0.2)  # 避免请求过于频繁
                    
            except Exception as e:
                print(f"   ❌ 删除记录 {record_id} 时发生错误: {e}")
        
        self.created_records.clear()
        print(f"✅ 清理完成，共删除 {deleted_count} 条记录")
    
    def demonstrate_record_lifecycle(self) -> None:
        """演示记录的完整生命周期"""
        print("\n🔄 记录生命周期演示...")
        
        # 1. 创建一个临时记录
        temp_record_data = {
            '编号': 'TEMP001',
            '商品名称': '临时测试商品',
            '价格': 99.99,
            '状态': '测试',
            '标签': ['测试'],
            '上架日期': '2024/03/01'
        }
        
        print("   1. 创建临时记录...")
        try:
            result = self.client.create_record(
                app_token=self.app_token,
                table_id=self.table_id,
                fields=temp_record_data
            )
            
            if result.get('code') != 0:
                print(f"   ❌ 创建失败: {result.get('msg')}")
                return
            
            temp_record = result.get('data', {}).get('record', {})
            temp_record_id = temp_record.get('record_id')
            print(f"   ✅ 创建成功: {temp_record_id}")
            
            # 2. 读取记录
            print("   2. 读取记录...")
            read_result = self.client.get_records(
                app_token=self.app_token,
                table_id=self.table_id,
                record_ids=[temp_record_id]
            )
            
            if read_result.get('code') == 0:
                records = read_result.get('data', {}).get('records', [])
                if records:
                    print(f"   ✅ 读取成功: {records[0].get('fields', {}).get('商品名称')}")
            
            # 3. 更新记录
            print("   3. 更新记录...")
            update_result = self.client.update_record(
                app_token=self.app_token,
                table_id=self.table_id,
                record_id=temp_record_id,
                fields={
                    '商品名称': '更新后的测试商品',
                    '价格': 199.99,
                    '状态': '已更新'
                }
            )
            
            if update_result.get('code') == 0:
                print("   ✅ 更新成功")
            
            # 4. 删除记录
            print("   4. 删除记录...")
            delete_result = self.client.delete_record(
                app_token=self.app_token,
                table_id=self.table_id,
                record_id=temp_record_id
            )
            
            if delete_result.get('code') == 0:
                print("   ✅ 删除成功")
            
            print("   🎉 记录生命周期演示完成！")
            
        except Exception as e:
            print(f"   ❌ 生命周期演示时发生错误: {e}")

def main():
    """主函数"""
    print("🚀 记录管理示例")
    print("=" * 50)
    
    # 从配置文件加载应用信息
    config = Config()
    
    # 创建客户端
    client = FeishuBitableClient(
        client_id=config.CLIENT_ID,
        client_secret=config.CLIENT_SECRET
    )
    
    # 确保有有效的访问令牌
    if not client.ensure_valid_token():
        print("❌ 无法获取访问令牌")
        return
    
    print("✅ 成功获取访问令牌")
    print()
    
    # 创建记录管理器
    record_manager = RecordManager(client, config.APP_TOKEN, config.TABLE_ID)
    
    try:
        # 1. 记录生命周期演示
        record_manager.demonstrate_record_lifecycle()
        
        # 2. 创建示例记录
        print("\n" + "=" * 50)
        created_records = record_manager.create_sample_records()
        
        # 3. 搜索记录演示
        print("\n" + "=" * 50)
        found_records = record_manager.search_records_demo()
        
        # 4. 批量获取记录演示
        print("\n" + "=" * 50)
        if record_manager.created_records:
            batch_records = record_manager.batch_get_records_demo(record_manager.created_records)
        
        # 5. 批量更新记录演示
        print("\n" + "=" * 50)
        if created_records:
            record_manager.update_records_demo(created_records)
        
        # 询问是否清理测试记录
        print("\n" + "=" * 50)
        cleanup = input("是否清理创建的测试记录？(y/N): ").lower().strip()
        if cleanup in ['y', 'yes', '是']:
            record_manager.cleanup_created_records()
        else:
            print("\n💡 测试记录已保留，可以手动删除或稍后清理")
            print(f"   创建的记录ID: {record_manager.created_records}")
        
        print("\n🎉 记录管理示例完成！")
        
    except KeyboardInterrupt:
        print("\n\n⚠️ 用户中断操作")
        cleanup = input("是否清理已创建的测试记录？(y/N): ").lower().strip()
        if cleanup in ['y', 'yes', '是']:
            record_manager.cleanup_created_records()
    
    except Exception as e:
        print(f"\n❌ 执行过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
        
        # 尝试清理
        try:
            record_manager.cleanup_created_records()
        except:
            pass

if __name__ == "__main__":
    main()